package com.adams.utils.threadpool;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.log4j.Logger;


public class DefaultTaskExecutor implements TaskExecutor {
	private ThreadPoolExecutor executor;
	
	Logger logger = Logger.getLogger(this.getClass());

	public DefaultTaskExecutor() {
		this.executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		this.executor.setThreadFactory(new ThreadFactory(){

			private UncaughtExceptionHandler handler = new UncaughtExceptionHandler(){

				@Override
				public void uncaughtException(Thread t, Throwable e) {
					
					logger.error(e);
				}
				
			};

			@Override
			public Thread newThread(Runnable r) {
				
				Thread thread = new Thread(r);
				thread.setUncaughtExceptionHandler(handler);
				return thread;
			}
			
		});

	}

	public DefaultTaskExecutor(ThreadPoolExecutor executor) {
		super();
		this.executor = executor;
	}

	@Override
	public void start() {

	}

	@Override
	public void stop() {

		this.executor.shutdown();
	}

	@Override
	public void submit(final Task task) {

		executor.execute(new Runnable() {

			@Override
			public void run() {

				task.execute();

			}

		});
	}

	@Override
	public boolean isAllTaskFinish() {
		return executor.getActiveCount()==0;
		//return ((ThreadPoolExecutor) executor).getQueue().isEmpty();
	}

}
